package com.zhhs.common.utils;


import com.zhhs.project.act.activity.domian.GiftVo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @description: 抽奖工具类
 * @author: JiaLe
 * @date: 2022-11-18 09:19
 **/
public class DrawUtils {

    public static GiftVo draw(List<GiftVo> gifts) {
        if (null == gifts || gifts.size() == 0) {
            return null;
        }

        gifts.sort((o1, o2) -> (o1.getProb() - o2.getProb()) > 0 ? 1 : -1);

        List<Double> probLists = new ArrayList<>(gifts.size());
        Double sumProb = 0D;
        for (GiftVo gift : gifts) {
            sumProb += gift.getProb();
        }
        if (sumProb <= 0) {
            return null;
        }

        // 归一化概率端点
        Double rate = 0D;
        for (GiftVo gift : gifts) {
            rate += gift.getProb();
            probLists.add(rate / sumProb);
        }

        double random = Math.random();
        probLists.add(random);
        Collections.sort(probLists);
        int index = probLists.indexOf(random);
        if (index >= 0) {
            return gifts.get(index);
        }
        return null;
    }


    public static void main(String[] args) {
        List<GiftVo> gifts = new ArrayList<>();
        GiftVo nothing = new GiftVo("谢谢惠顾", 0.7D);
        GiftVo vip = new GiftVo("XX会员1个月", 0.3D);
        gifts.add(nothing);
        gifts.add(vip);

        int a=0;
        for (int i = 0; i < 10000; i++) {
            GiftVo gift = draw(gifts);
            if (!"谢谢惠顾".equals(gift.getName())) {
                a++;
            }
        }
        System.out.println(a);

    }

}
